var ytState;
var voted = false;
var currentSongId;
var videoids;
var likes;
var dislikes;
var opinionsArray;
var titles;
var currentSongNumber;
var nSongs;
var user;
var currentSong;
var ffCheckTimer;
var ffTimer;
var ffOn=false;
var ffCheckOn=false;
var rwTimer;
var rwCheckTimer;
var rwOn=false;
var rwCheckOn=false;
var decisionStationKey;
var requestedStations;
var decision;
var showPlaylist = false;



function togglePlaylist()
{
  if (showPlaylist) {
    document.getElementById('PlaylistList').setAttribute('hidden','true');
    document.getElementById('PlaylistButton').innerText = 'Show';
    showPlaylist = false;
  }
  else {
    document.getElementById('PlaylistList').removeAttribute('hidden');
    document.getElementById('PlaylistButton').innerText = "Hide";
    showPlaylist = true;
  }
  
  
  
  
}

function fillInPlaylist() {
    plist = document.getElementById('PlaylistList');
    clearChildren(plist);
    for (var i = 0; i < nSongs; i++) {
        var listNode = document.createElement('li');
        listNode.appendChild(document.createTextNode(getSongTitleForNumber(i)));
        listNode.setAttribute('name',i);
        listNode.setAttribute('class','inactiveSong');
        listNode.setAttribute('onClick', "skipToSong(parseInt(this.getAttribute('name')))");
        plist.appendChild(listNode);
    }

}

function getRelatedVideos(title)
{
      $.ajax({
        url: serviceURLS.relatedsongs,
        data: currentSong,
        success: function(data) {
            gotRelatedVideos(data);
        },
        dataType: 'json'});
}

function gotRelatedVideos(data)
{
  rv = document.getElementById('relatedVideos');
  clearChildren(rv);
  nvids = data.length
  for (var i = 0; i < nvids; i++)
  {
    vid = data[i];
    vTitle = vid.title;
    vID = vid.id;
    vThumb = vid.thumb;
    vidDiv = document.createElement('div')
    img = document.createElement('img')
    img.src = vThumb;
    
    vidTitle = document.createElement('h3');
    vidTitle.innerText = vTitle;
    vidDiv.setAttribute('data-vidTitle',vTitle);
    vidDiv.setAttribute('data-vidID',vID);
    
    vidDiv.vidTitle = vTitle;
    
    vidDiv.appendChild(vidTitle);
    vidDiv.appendChild(img);
    vidDiv.onclick = function(){addRecommendedSong(this.getAttribute('data-vidID'),this.getAttribute('data-vidTitle'));};
    vidDiv.style.cursor = 'pointer';
    rv.appendChild(vidDiv);
  }
}

function addRecommendedSong(vidID,vidTitle)
{
  userkey = getUserKey();
  addData = {}
  addData[kr.stations.key] = station.key;
  addData[kr.songs.title] = vidTitle;
  addData[kr.songs.songid] = vidID;
  addData[kr.users.key] = userkey;
    $.ajax({
    url: serviceURLS.addsong,
    data: addData,
    success: function(data) {
      gotAddRecommendedSong(data);
    },
    dataType: 'html'
  });
}

function gotAddRecommendedSong(data)
{
  status = data;
  alert(status);
}

function skipToSong(songNumber)
{
    plistChildren = document.getElementById('PlaylistList').children;
    if (currentSongNumber >= 0)
      plistChildren[currentSongNumber].setAttribute('class','inactiveSong');
    currentSongNumber = songNumber;
    if (currentSongNumber == nSongs) {
        reloadSongs();
        return;
    }
    plistChildren[currentSongNumber].setAttribute('class','activeSong');
    voted = false;
    ytplayer = document.getElementById("ytPlayer");
    currentSong = songs[currentSongNumber];
    currentSongId = currentSong[kr.songs.songid];
    ytplayer.loadVideoById(currentSongId);
    updateTitle(currentSong[kr.songs.title]);
    updateLikes(currentSong[kr.songs.likes]);
    updateDislikes(currentSong[kr.songs.dislikes]);
    updateOpinions(currentSong[kr.songs.opinion]);
    updateComments(currentSong[kr.songs.comment]);
    updateSongAdder(currentSong[kr.songs.user]);
    getRelatedVideos(currentSong[kr.songs.title]);
    $( "#play" ).button( "option", {label: "pause",icons: {primary: "ui-icon-pause"}} );
}

function updateSongAdder(song)
{
  addDiv = document.getElementById('addedBy');
  clearChildren(addDiv);
  picUrl = song.picUrl;
  if (!picUrl) return;
  name = song.name;
  
  label = document.createElement('div');
  label.id = 'addedByLabel';
  
  pictureDiv = document.createElement('div');
  pictureDiv.id = 'addedByPicture';
  
  nameDiv = document.createElement('div');
  nameDiv.id = 'addedByName';
  
  label.innerText = "Added By: ";
  imgDiv = document.createElement('img');
  imgDiv.src = picUrl;
  pictureDiv.appendChild(imgDiv);
  nameDiv.innerText = name;
  
  addDiv.appendChild(label);
  addDiv.appendChild(nameDiv);
  addDiv.appendChild(pictureDiv);
}

function beginFF()
{
  if (ffOn || ffCheckOn)
  {
    endFF();
    return;
  }
  ffCheckOn = true;
  ffCheckTimer = setTimeout("activateFF()",300);
}

function activateFF()
{
  ffCheckOn = false;
  ffOn = true;
  seekAhead();
}

function seekAhead()
{

ytplayer = document.getElementById("ytPlayer");
ytplayer.seekTo(ytplayer.getCurrentTime() + 2,true);
ffTimer=setTimeout("seekAhead()",300);
}

function endFF()
{
  if (ffCheckOn) {
    clearTimeout(ffCheckTimer);
    ffCheckOn = false;
    ffOn = false;
    cueNextSong();
    return;
  }
  if (ffOn) {
    clearTimeout(ffTimer);
    ffOn = false;
    ffCheckOn = false;
    return;
  }
}

function beginRW()
{
  if (rwOn || rwCheckOn)
  {
    endRW();
    return;
  }
  rwCheckOn = true;
  rwCheckTimer = setTimeout("activateRW()",300);
}

function activateRW()
{
  rwCheckOn = false;
  rwOn = true;
  seekBehind();
}

function seekBehind()
{

ytplayer = document.getElementById("ytPlayer");
ytplayer.seekTo(ytplayer.getCurrentTime() - 4,true);
rwTimer=setTimeout("seekBehind()",1000);
}

function endRW()
{
  if (rwCheckOn) {
    clearTimeout(rwCheckTimer);
    rwCheckOn = false;
    rwOn = false;
    cueNextSong();
    return;
  }
  if (rwOn) {
    clearTimeout(rwTimer);
    rwOn = false;
    rwCheckOn = false;
    return;
  }
}


function getSongTitleForNumber(i) {
  return songs[i][kr.songs.title];
}



function addStationsToSearchBox()
{
  nStations = stations.length;
  combobox = document.getElementById("combobox");
  clearChildren(combobox);
  addNewStationToStationSelector(station.name,'NULL');
  
  for (var i = 0; i < nStations; i++)
  {
    newstat = stations[i];
    if (newstat[kr.stations.name] == station.name) continue;
    addNewStationToStationSelector(newstat[kr.stations.name],newstat[kr.stations.key])
  }
  
}


function onPlayerStateChange(newState) {
    ytplayer = document.getElementById("ytPlayer");
    ytState=newState;
    if (ytState==2) {
    } else if (ytState==0) {
        cueNextSong();
    }
}

function Rewind() {
    ytplayer = document.getElementById("ytPlayer");
    ytplayer.seekTo(0,true);
}

function PreviousSong() {
    if (currentSongNumber == 0) {
        Rewind();
        return;
    }
    skipToSong(currentSongNumber-1);
}

function Play() {
    ytplayer = document.getElementById("ytPlayer");
    ytplayer.playVideo();
}

function onError(error) {
    cueNextSong();
}

function Pause() {
    ytplayer = document.getElementById("ytPlayer");
    ytplayer.pauseVideo();
}

function reloadSongs() {
    currentSongNumber = -1;
    rqData = new Object;
    rqData[kr.stations.key] = station.key;
    $.ajax({
        url: serviceURLS.getsongids,
        success: onReloadSongs,
        data: rqData,
        dataType: 'json'});
}

function onReloadSongs(data) {
    songs = data
    nSongs = songs.length;
    fillInPlaylist();
    if (nSongs < 1) return;
    cueNextSong();
}

function AddOpinion(op) {
    if (voted)
        return;
    voted = true;
    rqData = new Object;
    rqData[kr.opinions.like] = op;
    userkey = getUserKey();
    rqData[kr.users.key] = userkey;
    rqData[kr.songs.key] = currentSong[kr.songs.key];
    rqData[kr.opinions.songid] = currentSong[kr.songs.songid];
    $.ajax({
        url: serviceURLS.addopinion,
        data: rqData,
        success: function(data) {
            updateSong(data);
        },
        dataType: 'json'});
}

function getUserKey()
{
      if (!user || !user.key)
    {
      userkey = 'none';
    }
    else {
      userkey = user.key;
    }
    return userkey;
}

function updateSong(song)
{
  songs[currentSongNumber] = song;
  currentSong = song;
  updateTitle(currentSong[kr.songs.title]);
  updateLikes(currentSong[kr.songs.likes]);
  updateDislikes(currentSong[kr.songs.dislikes]);
  updateOpinions(currentSong[kr.songs.opinion]);
  updateComments(currentSong[kr.songs.comment]);
}

function updateLikes(data) {
    if (data.nLikes) {
        var n = data.nLikes;
        $( "#like" ).button( "option", "label",n);
        updateOpinions(data.opinions);
    } else {
        var n = data;
        $( "#like" ).button( "option", "label",n);
    }
}

function updateDislikes(data) {
    if (data.nDislikes) {
        var n = data.nDislikes;
        $( "#dislike" ).button( "option", "label",n);
        updateOpinions(data.opinions);
    } else {
        var n = data;
        $( "#dislike" ).button( "option", "label",n);
    }
}

function updateOpinions(ops) {
    if (!ops)
        return;
    var nOps = ops.length;
    var likePics = document.getElementById('likePics');
    var dislikePics = document.getElementById('dislikePics');
    clearChildren(likePics);
    clearChildren(dislikePics);

    for (var i = 0; i < nOps; i++) {
        var wrapper = document.createElement('div');
        var pic = document.createElement('img');
        var name = document.createElement('div')

        wrapper.setAttribute('id','opWrapper');
        pic.setAttribute('id','opPic');
        pic.setAttribute('src',ops[i].picUrl);
        name.setAttribute('id','opName');
        name.appendChild(document.createTextNode(ops[i].name));
        wrapper.appendChild(name);
        wrapper.appendChild(pic);

        if (ops[i].opinion)
            likePics.appendChild(wrapper);
        else
            dislikePics.appendChild(wrapper);
    }

}

function clearChildren(node) {
    if ( node.hasChildNodes() ) {
        while ( node.childNodes.length >= 1 ) {
            node.removeChild( node.firstChild );
        }
    }

}

function updateTitle(title) {
    $('#currentTitle').html('<h3>' + title + '</h3>');
}

function login() {
    FB.api('/me',{fields: "id,name,picture"}, function(response) {
        user ={type:'facebook',name:response.name,id:response.id,picUrl:response.picture};
        updateCommentsFB(user);
        registerUser();
        enableCommenting();
        enableAddStation();
    }
    );
}

function enableAddStation()
{
  document.getElementById('addStationButton').hidden = false;
}

function disableAddStation()
{
  document.getElementById('addStationButton').hidden = true;
}



function updateUserSectionAndAddUserStations()
{
  document.getElementById('USName').innerText = user.name;
  var userData = {};
  userData[kr.users.key] = getUserKey();
  $.ajax({
    url: serviceURLS.requestedstations,
    data: userData,
    success: function(data) {
      updateRequestedStations(data);
    },
    dataType: 'json'
  });
}

function addUserStations(stations)
{
  nStations = stations.length;
  combobox = document.getElementById("combobox");
  for (var i = 0; i < nStations; i++)
  {
    newstat = stations[i];
    addNewStationToStationSelector(newstat[kr.stations.name],newstat[kr.stations.key])
  }
}

function updateRequestedStations(data)
{
  rsDiv = document.getElementById('USRequestedStations');
  rs = data[kr.users.requestedStations];
  var stats = data[kr.users.stations];
  addUserStations(stats);
  requestedStations = rs;
  nStations = rs.length;
  clearChildren(rsDiv);
  if (nStations == 0) return;
  rsDiv.innerHTML = '<h3>Station Invitations</h3>';
  
  for (var i = 0; i < nStations; i++)
  {
    statData = rs[i];
    owner = statData[kr.stations.owner];
    ownerName = owner[kr.users.user];
    ownerPic = owner[kr.users.picUrl];
    statName = statData[kr.stations.name];
    public = statData[kr.stations.public];
    statKey = statData[kr.stations.key];
    
    statDiv = document.createElement('div');
    statDiv.setAttribute('id','RS - ' + statKey);
    statDiv.setAttribute('border','2');
    
    
    
    ownerDiv = document.createElement('div');
    
    picDiv = document.createElement('img');
    picDiv.setAttribute('src', ownerPic);
    
    ownerNameDiv = document.createElement('div');
    ownerNameDiv.appendChild(document.createTextNode(ownerName));
    
    ownerDiv.appendChild(picDiv);
    ownerDiv.appendChild(ownerNameDiv);
    
    publicDiv = document.createElement('div');
    publicDiv.appendChild(document.createTextNode('Public: ' + public));
    
    statNameDiv = document.createElement('div');
    statNameDiv.appendChild(document.createTextNode(statName));
    
    chooseDiv = document.createElement('div');
    
    acceptDiv = document.createElement('div');
    acceptDiv.setAttribute('name',statKey);
    acceptDiv.setAttribute('onClick','stationRequestDecision(this.getAttribute("name"),true)');
    acceptDiv.innerText = "Accept";
    
    rejectDiv = document.createElement('div');
    rejectDiv.setAttribute('name',statKey);
    rejectDiv.setAttribute('onClick','stationRequestDecision(this.getAttribute("name"),false)');
    rejectDiv.innerText = "Reject";
    
    chooseDiv.appendChild(acceptDiv);
    chooseDiv.appendChild(rejectDiv);
    
    statDiv.appendChild(statNameDiv);
    statDiv.appendChild(publicDiv);
    statDiv.appendChild(ownerDiv);
    statDiv.appendChild(chooseDiv);
    
    rsDiv.appendChild(statDiv);
    
    
    
  }
  
}

function stationRequestDecision(statKey,dec)
{
  decisionStationKey = statKey;
  decision = dec;
  sendData = {};
  sendData[kr.stations.key] = statKey;
  sendData['decision'] = dec;
  sendData[kr.users.key] = getUserKey();
  $.ajax({
    url: serviceURLS.stationrequestdecision,
    data: sendData,
    success: function(data) {
      decisionResponse(data);
    },
    dataType: 'html'
  });
}

function decisionResponse(data)
{
  removedElement = document.getElementById('RS - ' + decisionStationKey);
  removedElement.parentNode.removeChild(removedElement);
  if (!decision) return;
  stationName = getRSStationNameFromKey(decisionStationKey);
  addNewStationToStationSelector(stationName,decisionStationKey);
}

function addNewStationToStationSelector(name,key)
{
  
  combobox = document.getElementById("combobox");
  var optionBox = document.createElement('option')
  optionBox.setAttribute('value',key);
  var textnode = document.createTextNode(name);
  optionBox.appendChild(textnode);
  combobox.appendChild(optionBox);
}

function getRSStationNameFromKey(dsk)
{
  nStations = requestedStations.length;
  for (var i = 0; i < nStations; i++)
  {
    stat = requestedStations[i];
    if (stat[kr.stations.key] == dsk)
    {
      return stat[kr.stations.name];
    }
  }
}

function enableCommenting() {
    var cForm = document.getElementById('commentForm');
    cForm.elements[2].disabled = false;
    var cLabel = document.getElementById('commentLabel');
    cLabel.removeChild(cLabel.firstChild);
}

function registerUser() {
    $.ajax({
        url: serviceURLS.registeruser,
        data: user,
        success: function(data) {
            updateUser(data);
        },
        dataType: 'html'});
}

function updateUser(data) {
  user.key = data;
  updateUserSectionAndAddUserStations();
}

function logout() {
  user = null;
    disableComments();
    disableAddStation();
}

function disableComments() {
    var picDiv = document.getElementById('posterPic');
    clearChildren(picDiv);
    var cForm = document.getElementById('commentForm');
    cForm.elements[2].disabled = true;
    var cLabel = document.getElementById('commentLabel');
    cLabel.appendChild(document.createTextNode('Login With Facebook to Comment!'));
}

function updateCommentsFB(user) {
    var picDiv = document.getElementById('posterPic');
    clearChildren(picDiv);
    var cForm = document.getElementById('commentForm');
    cForm.elements[0].value = user.name;
    var oImg=document.createElement("img");
    oImg.setAttribute('src', user.picUrl);
    picDiv.appendChild(oImg);
    cForm.elements[0].disabled = true;
}

function updateComments(comments) {
    var nComments = comments.length;
    var commentsSection = document.getElementById("comments");

    clearChildren(commentsSection);

    for (var i = 0; i < nComments; i++) {
        var posterNode = document.createElement('div');
        var commentNode = document.createElement('div');
        var wrapperNode = document.createElement('div');
        var picNode = document.createElement('img');
        var picUrl = comments[i][kr.users.picUrl];
        var poster = document.createTextNode(comments[i][kr.comments.date] + ' -- ' + comments[i][kr.comments.poster]);
        var comment = document.createTextNode(comments[i][kr.comments.comment]);

        commentNode.setAttribute('id','commentText');
        commentNode.appendChild(comment);
        picNode.setAttribute('id','commentPic');
        picNode.setAttribute('src',picUrl);
        posterNode.setAttribute('id','poster');
        posterNode.appendChild(picNode);
        posterNode.appendChild(poster);
        wrapperNode.setAttribute('id','comment');
        wrapperNode.appendChild(posterNode);
        wrapperNode.appendChild(commentNode);
        commentsSection.appendChild(wrapperNode);
    }
}

function postComment(cForm) {
    var poster = cForm.elements[0].value;
    var comment = cForm.elements[1].value;
    cForm.elements[1].value = '';
    if (comment == '')
        return;
    var rd = new Object;
    rd[kr.comments.songid] = currentSong[kr.songs.songid];
    rd[kr.songs.key] = currentSong[kr.songs.key]
    rd[kr.comments.comment] = comment;
    rd[kr.stations.name] = station.name;
    rd[kr.users.key] = getUserKey();
    
    $.ajax({
        url: serviceURLS.postcomment,
        data: rd,
        success: function(data) {
            updateSong(data);
        },
        dataType: 'json'});

}

function cueNextSong() {
  skipToSong(currentSongNumber+1);
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("ytPlayer");
    ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
    reloadSongs();
}

function InitVideoPlayer() {

    var params = { allowScriptAccess: "always" };
    var atts = { id: "ytPlayer" };
    swfobject.embedSWF("http://www.youtube.com/apiplayer?" +
    "&enablejsapi=1&playerapiid=mojplayer",
    "videoBox", "600", "400", "8", null, null, params, atts);
}

function setupToolbar() {

    $( function() {
        $( "#previous" ).button({
            text: false,
            icons: {
                primary: "ui-icon-seek-start"
            }
        })
        .click( function() {
            PreviousSong();
        });
        $( "#rewind" ).button({
            text: false,
            icons: {
                primary: "ui-icon-seek-prev"
            }
        })
        .mousedown(function() {
          beginRW();
            })
        .mouseup(function() {
          endRW();
        })
        .mouseleave(function() {
          endRW();
        })
        ;
        $( "#play" ).button({
            text: false,
            icons: {
                primary: "ui-icon-play"
            }
        })
        .click( function() {
            var options;
            if ( $( this ).text() === "play" ) {
                Play();
                options = {
                    label: "pause",
                    icons: {
                        primary: "ui-icon-pause"
                    }
                };
            } else {
                Pause();
                options = {
                    label: "play",
                    icons: {
                        primary: "ui-icon-play"
                    }
                };
            }
            $( this ).button( "option", options );
        });
        $( "#next" ).button({
            text: false,
            icons: {
                primary: "ui-icon-seek-next"
            }
        })
        .mousedown(function() {
          beginFF();
            })
        .mouseup(function() {
          endFF();
        })
        .mouseleave(function() {
          endFF();
        })
        ;
        $( "#like" ).button({
            icons: {
                primary: "ui-icon-arrowthick-1-n"
            }
        })
        .click( function() {
            AddOpinion(true);
        });
        $( "#dislike" ).button({
            icons: {
                primary: "ui-icon-arrowthick-1-s"
            }
        })
        .click( function() {
            AddOpinion(false);
        });
    });
}
function onJQReady() {
    setupToolbar();
    InitVideoPlayer();
    addStationsToSearchBox();
    (function( $ ) {
        $.widget( "ui.combobox", {
            _create: function() {
                var self = this,
                select = this.element.hide(),
                selected = select.children( ":selected" ),
                value = selected.val() ? selected.text() : "";
                var input = $( "<input>" )
                .insertAfter( select )
                .val( value )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( select.children( "option" ).map( function() {
                            var text = $( this ).text();
                            if ( this.value && ( !request.term || matcher.test(text) ) )
                                return {
                                    label: text.replace(
                                    new RegExp(
                                    "(?![^&;]+;)(?!<[^<>]*)(" +
                                    $.ui.autocomplete.escapeRegex(request.term) +
                                    ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>" ),
                                    value: text,
                                    option: this
                                };
                        }) );
                    },
                    select: function( event, ui ) {
                        ui.item.option.selected = true;
                        self._trigger( "selected", event, {
                            item: ui.item.option
                        });
                        openStation(event,ui);
                    },
                    change: function( event, ui ) {
                        if ( !ui.item ) {
                            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                            valid = false;
                            select.children( "option" ).each( function() {
                                if ( this.value.match( matcher ) ) {
                                    this.selected = valid = true;
                                    return false;
                                }
                            });
                            if ( !valid ) {
                                // remove invalid value, as it didn't match anything
                                $( this ).val( "" );
                                select.val( "" );
                                return false;
                            }
                        }
                    }
                })
                .addClass( "ui-widget ui-widget-content ui-corner-left" );

                input.data( "autocomplete" )._renderItem = function( ul, item ) {
                    return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.label + "</a>" )
                    .appendTo( ul );
                };
                $( "<button>&nbsp;</button>" )
                .attr( "tabIndex", -1 )
                .attr( "title", "Show All Items" )
                .insertAfter( input )
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass( "ui-corner-all" )
                .addClass( "ui-corner-right ui-button-icon" )
                .click( function() {
                    // close if already visible
                    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                        input.autocomplete( "close" );
                        return;
                    }

                    // pass empty string as value to search for, displaying all results
                    input.autocomplete( "search", "" );
                    input.focus();
                });
            }
        });
    })( jQuery );
    $( function() {
        $("#combobox").combobox({
            select: function(event, ui) {
                openStation(event,ui);
            }
        });
        $( "#combobox" ).combobox();
    });
}

function openStation(event,ui) {
    if (ui.item) {
        if (ui.item.option.value == 'NULL')
            return;
        window.location.replace(serviceURLS.main + "?" + kr.stations.key + "=" + ui.item.option.value.replace(' ','+'));
    }
}

$().ready(onJQReady);